package utils.file;

import utils.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by lining on 2018/1/24.
 */
public class FileDownloadUtils {

    /**
     * 下载远程文件并保存到本地
     *
     * @param remoteFilePath 远程文件路径
     * @param localFilePath  本地文件路径
     */
    public static Map<String,Object> downloadFile(String remoteFilePath, String localFilePath) {
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        Map<String,Object> fileInfo = new HashMap<>();
        try {
            urlfile = new URL(remoteFilePath);
            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.connect();

            String pattern = "\\.(\\w+)\\?|\\.(\\w+)$";
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(remoteFilePath);
            if(m.find())localFilePath += (m.group(0).split("\\?")[0]);//获取下载路径中的扩展名

            File f = new File(localFilePath);
            fileInfo.put("Content-Type",httpUrl.getHeaderField("Content-Type"));
            fileInfo.put("Content-Disposition",httpUrl.getHeaderField("Content-Disposition"));
            fileInfo.put("remoteFilePath",remoteFilePath);
            fileInfo.put("localFilePath",localFilePath);
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            bos.flush();
            bis.close();
            httpUrl.disconnect();
            fileInfo.put("file",f);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileInfo;
    }

    public static File downloadRemoteFile(String remotePath, String localPath) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            HttpURLConnection httpUrl = (HttpURLConnection) new URL(remotePath).openConnection();
            httpUrl.connect();
            File file = new File(localPath);
            File fileDir = new File(file.getParent());
            if(!fileDir.exists())fileDir.mkdirs();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(file));
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            bos.flush();
            httpUrl.disconnect();
            return file;
        } catch (Exception e) {
            System.out.printf("=== download file error:remotePath=%s,localPath=%s,error=%s",remotePath,localPath,e);
        } finally {
            try {
                bis.close();
                bos.close();
            } catch (IOException e) {
                System.out.printf("=== stream close error:remotePath=%s,localPath=%s,error=%s", remotePath, localPath, e);
            }
        }
        return null;
    }

    public static File downloadRemoteFile2(String remotePath, String localPath) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            HttpURLConnection httpUrl = (HttpURLConnection) new URL(remotePath).openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());

            String fileType = FileTypeUtils.getFileTypeByRemoteUrl(remotePath);

            int len = 50;
            byte[] b = null;
            if (StringUtils.isNullOrEmpty(fileType)) {
                b = new byte[len];
                len = bis.read(b);
                fileType = FileTypeUtils.getFileTypeByStream(b);
            }

            if (!StringUtils.isNullOrEmpty(fileType)) {
                localPath += "." + fileType;
            }

            File file = new File(localPath);
            File fileDir = new File(file.getParent());
            if (!fileDir.exists()) fileDir.mkdirs();

            bos = new BufferedOutputStream(new FileOutputStream(file));
            //1、通过文件获取扩展名没读完，2、通过url获取扩展名没读
            if (len != -1) {
                if (b != null) bos.write(b, 0, len);//没读b为null
                len = 2048;
                b = new byte[len];
                while ((len = bis.read(b)) != -1) {
                    bos.write(b, 0, len);
                }
            }

            bos.flush();
            httpUrl.disconnect();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        downloadRemoteFile2("http://fox-1252015034.cossh.myqcloud.com/image/jpeg/%E8%BA%AB%E4%BB%BD%E8%AF%81%E5%8F%8D%E9%9D%A2%E7%85%A7%E7%89%87-JuFfYYkH.jpg","/Users/lining/Desktop/pdftest/test2");
    }
}
